﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using Crude.Common;
using System.IO;
using Crude.Core.Repository;

namespace Crude.Core
{
    public class ThirdPartyAssembliesTool
    {       
        public void PublishAssemblies(IList<string> assembliesFilePath)
        {
            HashSet<string> frameworkAssemblies = FrameworkUtility.GetFrameworkAssemblies();

            foreach (string assemblyFilePath in assembliesFilePath)
            {
                Assembly assembly = Assembly.ReflectionOnlyLoadFrom(assemblyFilePath);
                AssemblyName assemblyName = assembly.GetName();

                FileInfo fileInfo = new FileInfo(assemblyFilePath);

                ProjectObjectModel pom = new ProjectObjectModel();
                pom.Name = assemblyName.Name;
                pom.Version = assemblyName.Version.ToString();
                pom.MainOutputFile = string.Format("{0}{1}", assemblyName.Name, fileInfo.Extension);

                foreach (AssemblyName referencesAssembly in assembly.GetReferencedAssemblies())
                {
                    if (!frameworkAssemblies.Contains(referencesAssembly.Name.ToLower()))
                    {
                        ProjectDependency dependency = new ProjectDependency();
                        dependency.Name = referencesAssembly.Name;
                        dependency.Version = referencesAssembly.Version.ToString();

                        pom.Dependencies.Add(dependency);
                    }
                }

                IRemoteRepository remoteRepository = new RemoteRepositoryBuilder().Build();

                string pomFilePath = System.IO.Path.GetTempFileName();

                new ProjectObjectModelSaver().Save(pomFilePath, pom);

                if (pom.MainOutputFile != fileInfo.Name)
                {       
                    string newFileName = string.Format("{0}\\{1}", Path.GetTempPath(), pom.MainOutputFile);

                    File.Copy(fileInfo.FullName, newFileName, true);

                    fileInfo = new FileInfo(newFileName);
                }

                remoteRepository.UploadProject(pomFilePath, fileInfo.Directory.FullName, pom); 
            }

        }
    }
}
